<template>
    <d2-container>
        <el-form :inline="true" >
           <div style="font-weight: 10px;font-size: 20px">员工在考勤范围内可打卡上班</div>
            
                <el-button type="primary" style="float:right;margin-bottom: 10px" icon="el-icon-plus" @click='showLocation'>新增考勤地点</el-button>
        </el-form>
        <el-table :data="dataList" border style="width: 100%">
            <el-table-column prop="name" label="考勤地点名称"></el-table-column>
           
            <el-table-column  label="经纬度">
                <template slot-scope='scope'>
                    {{scope.row.longitude}} , {{scope.row.latitude}}
                </template>
            </el-table-column>
            <el-table-column prop="distance" label="距离(m)"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column prop="memo" label="备注"></el-table-column>
            <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button @click="editClick(scope.row)" type="text" size="small">修改</el-button>
                    <el-button @click="deleteClick(scope.row)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
           <el-dialog title="选择坐标" :visible.sync="addLocation">
                <span style='display: inline-block;width: 20%;font-size: 16px;margin-bottom: 15px'>考勤地点名称：</span>
                <el-input placeholder="考勤地点名称" v-model="newLocationName" size="small" style='display: inline-block;width: 70%' required>
                </el-input>
                <span style='display: inline-block;width: 20%;font-size: 16px;margin-bottom: 15px'>范围(m)</span>
                <el-input placeholder="范围(m)" v-model="distance" size="small" style='display: inline-block;width: 70%' type='number' step='1' min=1>
                </el-input>
                <span style='display: inline-block;width: 20%;font-size: 16px;margin-bottom: 15px'>地址：</span>
                <el-input placeholder="地址，选填" v-model="address" size="small" style='display: inline-block;width: 70%'>
                </el-input>
                <span style='display: inline-block;width: 20%;font-size: 16px;margin-bottom: 15px'>备注：</span>
                <el-input placeholder="备注，选填" v-model="memo" size="small" style='display: inline-block;width: 70%'>
                </el-input>
                <div id="container123" style="margin-top:20px;width:300px;height:300px;"></div>

      <h3>搜索地址</h3>
        <el-input placeholder="请输入地址" v-model="address"  style="width:600px">
          <el-button slot="append" icon="el-icon-search" @click="searchAddress"></el-button>
        </el-input>

      <h3>经度</h3>
      <el-input
              placeholder=""
              min="0"
              v-model="newLocationLongitude"
      ></el-input>

      <h3>纬度</h3>
      <el-input
              placeholder=""
              min="0"
              v-model="newLocationLatitude"
      ></el-input>
      <el-button style='margin-top: 20px;' type='primary' @click='addWorkRecordLocation'>确定</el-button>
      <el-button style='margin-top: 20px;' @click='addLocation = false'>取消</el-button>
            </el-dialog>
    </d2-container>
</template>

<script>
    import request from "@/plugin/axios";
        import {mapState} from "vuex";

    export default {
        data() {
            return {
                dataList: [],
                total: 0,
                pageSize: 10,
                currentPage: 1,
                dataSearch: {},
                addLocation : false,
                newLocationName : '',
                newLocationLatitude : 0,
                newLocationLongitude : 0,
                address : '',
                memo : '',
                city :'',
                distance : 50,
                headquarter : false,
                id : undefined
            };
        },
         computed: {
            ...mapState('d2admin/user', ['info']),
        },
        methods: {
            
            editClick(row){
              this.id = row._id
              this.newLocationName = row.name
              this.newLocationLatitude = row.latitude
              this.newLocationLongitude = row.longitude
              this.distance = row.distance
              this.address = row.address
              this.addLocation = true
            },
            
            addWorkRecordLocation(){
                if (this.newLocationName == '' ){
                    this.$alert('','考勤地点名称不能为空')
                    return false
                }
                if ((this.newLocationLatitude == 0) || (this.newLocationLongitude == 0)){
                    this.$alert('','考勤地点坐标不能为空')
                    return false
                }
                let url = "/workRecordGroup/addWorkRecordLocation"
                let data = {}
                data.memo = this.memo
                data.address = this.address
                data.city = this.city
                data.name = this.newLocationName
                data.latitude = this.newLocationLatitude
                data.longitude = this.newLocationLongitude
                data.distance = this.distance
                data.school = this.school
                if (this.id != undefined){
                  url = "/workRecordGroup/updateWorkRecordLocation"
                  data.id = this.id
                }
                request({
                            url: url,
                            method: "post",
                            data: data
                        }).then(res => {
                            if (res.code == 200){
                                this.getDataList()
                                this.city = ''
                                this.newLocationLatitude = 0
                                this.newLocationLongitude = 0
                                this.newLocationName = ''
                                this.distance = 50
                                this.addLocation = false
                                this.id = undefined
                                this.$message('操作成功！')
                            }
                        })

            },

            deleteClick(e) {
                this.$confirm("此操作将删除该考勤地点, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        if (e._id == undefined){
                            this.dataList.splice(this.dataList.map(function(e){return e._id}).indexOf(e._id),1)
                            return false
                        }
                        request({
                            url: "/workRecordGroup/deleteWorkRecordLocation",
                            method: "post",
                            data: {id: e._id}
                        }).then(res => {
                            if (res.code == 200) {
                                this.$message({
                                    message: "删除成功"
                                });
                                this.getDataList(this.dataSearch);
                            }
                        });
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
            },

            getDataList() {
                // var datax = data
                // datax.school = this.school
                let data ={}
                if (!this.headquarter){
                  data.school = this.school
                }
                request({
                    url: "/workRecordGroup/getWorkRecordLocationList",
                    method: "post",
                    data: data
                }).then(res => {
                    this.dataList = [];
                    this.dataList = res.data;

                });
            },

        searchAddress(){
      let that = this
      let geocoder = new qq.maps.Geocoder({
        complete: function(result) {
          console.log(result)
          let position = {}
          that.newLocationLatitude = result.detail.location.lng,//经度
          that.newLocationLongitude = result.detail.location.lat,//纬度
          position.lat = result.detail.location.lat
          position.lng = result.detail.location.lng
          position.city = result.detail.addressComponents.city
          that.showPosition(position)
        },
        //若服务请求失败，则运行以下函数
        error: function(result) {
            alert("出错了，请输入详细的地址（包含省市）！！！");
        }
      });
      geocoder.getLocation(this.address);
    },

    showLocation(){
        this.addLocation = true
        this.city = ''
                                this.newLocationLatitude = 0
                                this.newLocationLongitude = 0
                                this.newLocationName = ''
                                this.distance = 50
                                this.id = undefined
        this.getMyLocation()

    },


    //定位获得当前位置信息
    getMyLocation() {
      let geolocation = new qq.maps.Geolocation("ANPBZ-OZFWO-6NIWX-SILNK-4RQT5-3SFFW", "弈飞围棋");
      geolocation.getIpLocation(this.showPosition, this.showErr);
    },

    showPosition(position) {
      this.newLocationLatitude = position.lat;
      this.newLocationLongitude = position.lng;
      this.city = position.city;
      this.setMap(position.lat,position.lng);
    },

    showErr() {
      this.getMyLocation();//定位失败再请求定位，测试使用
    },

//第二部分
    //位置信息在地图上展示
    setMap(latitude,longitude) {
      //步骤：定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
      //设置地图中心点

      let myLatlng = new qq.maps.LatLng(latitude,longitude);

      //定义工厂模式函数
      let myOptions = {
        zoom: 13,               //设置地图缩放级别
        center: myLatlng,    //设置中心点样式
        mapTypeId: qq.maps.MapTypeId.ROADMAP  //设置地图样式详情参见MapType
      }
      // //获取dom元素添加地图信息
      let  map = new qq.maps.Map(document.getElementById("container123"), myOptions);


      let marker = new qq.maps.Marker({
        position: new qq.maps.LatLng(latitude,longitude),
        map: map
      });
      var _this = this

      qq.maps.event.addListener(map,'click',function (event) {

        marker.setMap(null);
        _this.newLocationLongitude = parseFloat(event.latLng.getLng()).toFixed(6);
        _this.newLocationLatitude = parseFloat(event.latLng.getLat()).toFixed(6);
        marker=new qq.maps.Marker({
          position:new qq.maps.LatLng(event.latLng.getLat(),event.latLng.getLng()),
          map:map
        });
      })
        },
    },
        created() {
          let school = this.info.school[0]
          this.school = school._id
          if ((school.headquarter == 1) ||(school.headquarter == 2)){
            this.headquarter = true
            // this.$alert('如果有打卡地点增减需求，请连续主校区。','该功能不对分校开放')
            // return false
          }
          this.getDataList();
          
        }
    };
</script>
